#include <pthread.h>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>
#include "RingQueue.hpp"
#include "Task.hpp"
using namespace std;


string SelfName()
{
    char name[128];
    snprintf(name, sizeof(name), "thread[0x%x]", pthread_self());
    return name;
}

void *ProductorRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task>*>(rq);
    while(true)
    {
        int x = rand() % 10;
        int y = rand() % 10;
        char op = oper[rand()%oper.size()];
        Task t(x, y, op, mymath); //生产任务

        ringqueue->Push(t);

        cout <<  SelfName() << " 生产者派发了一个任务: " << t.toTaskString() <<endl;

         sleep(1);
    }
}

void *ConsumerRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);

    while(true)
    {
        Task t;
        ringqueue->Pop(&t); //消费任务
        string result = t(); // 消费也是要花时间的！
        cout <<SelfName() << " 消费者消费了一个任务: " << result <<endl;

        //sleep(1);
    }
}

int main()
{
    srand((unsigned int)time(nullptr)^getpid()^666);
    RingQueue<Task> *rq = new RingQueue<Task>();

    pthread_t p[4], c[8];
    for(int i = 0; i < 4; i++) pthread_create(p+i, nullptr, ProductorRoutine, rq);
    for(int i = 0; i < 8; i++) pthread_create(c+i, nullptr, ConsumerRoutine, rq);

    for(int i = 0; i < 4; i++) pthread_join(p[i], nullptr);
    for(int i = 0; i < 8; i++) pthread_join(c[i], nullptr);
    delete rq;
    return 0;
}